##############################################################################
##############################################################################
##############################################################################
##############################################################################
## Code to install R packages and dependencies used by:
## Lyall and Zhukov, "Fratricidal Coercion in Modern War"
##############################################################################
##############################################################################
##############################################################################
##############################################################################

# Print upon starting
print("**** Starting run1_setup.R ****")

## Detach non-essential packages
detachAllPackages <- function() {
  basic.packages <- c("package:stats","package:graphics","package:grDevices","package:utils","package:datasets","package:methods","package:base")
  package.list <- search()[ifelse(unlist(gregexpr("package:",search()))==1,TRUE,FALSE)]
  package.list <- setdiff(package.list,basic.packages)
  if (length(package.list)>0)  for (package in package.list) detach(package, character.only=TRUE)
}
detachAllPackages()
rm(detachAllPackages)

## Install and load packages
list.of.packages <- c("data.table","dplyr","stringr","parallel","lfe","lme4","nlme","Formula","xtable","optimx","splines","ggplot2","robustlmm","Matching","fixest","SUNGEO","tidyselect")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]; if(length(new.packages)){install.packages(new.packages,dependencies=TRUE,repos="http://cran.us.r-project.org")}
loaded.packages <- lapply(list.of.packages, require, character.only = TRUE)
rm(list.of.packages,new.packages,loaded.packages)

# Turn off s2 processing
suppressMessages({
  sf::sf_use_s2(FALSE)
})

# Disable scientific notation
options(scipen=999)

# Print upon finishing
print("**** Finished run1_setup.R ****")

